package com.cj.td.common.util.ini;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.loon.framework.android.game.utils.StringUtils;

import android.content.Context;

public class IniReaderHasSection {
	private Map<String,Properties> sections;
	
	private String section;
	
	private Properties properties;
	
	public IniReaderHasSection(String fileName) throws IOException{
		sections = new HashMap<String, Properties>();
		BufferedReader reader = new BufferedReader(new FileReader(fileName));
		read(reader);
		reader.close();
	}
	
	/**
	 * 读取asset文件
	 * @param context
	 * @param iniPath
	 */
	public IniReaderHasSection(Context context,String iniPath){
		try{
			sections = new HashMap<String, Properties>();
			InputStream inputStream = context.getResources().getAssets().open(iniPath);
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			read(reader);
			reader.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
	}
	private void read(BufferedReader reader)  throws IOException{
		String line;
		while((line = reader.readLine())!=null){
			parseLine(line);
		}
	}

	private void parseLine(String line) {
		line = line.trim();
		if(line.matches("\\[.*\\]")==true){
			section = line.replaceFirst("\\[(.*)\\]", "$1");
			properties = new Properties();
			sections.put(section.toLowerCase(), properties);
		}else{
			if(properties!=null
					&&!line.startsWith(";")
					&&!StringUtils.isEmpty(line)){
				int i = line.indexOf('=');
				String name = line.substring(0,i-1).trim();
				String value = line.substring(i+1).trim();
				properties.setProperty(name.toLowerCase(), value);
			}
		}
	}
	
	public String getValue(String section,String name){
		Properties p = sections.get(section.toLowerCase());
		
		if(p == null)return null;
		
		return p.getProperty(name.toLowerCase());
	}
}
